﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CoyoEden{
	public static partial class Utils
	{
		/// <summary>
		/// Iterate Through a Directory Tree,Get all files with specified extension
		/// </summary>
		/// <param name="path">A directory path,such as "c:\"</param>
		/// <param name="extName">file extension name.such as ".mp3.cs.htm"</param>
		/// <returns></returns>
		public static List<FileInfo> GetFiles(string path, string extName) {
			List<FileInfo> files = new List<FileInfo>();
			files.AddRange(WalkDirecotry(path, extName));
			return files;
		}
		#region helper methods
		private static List<FileInfo> WalkDirecotry(string path, string extName) {
			List<FileInfo> retVal = new List<FileInfo>();
			try {
				string[] dir = Directory.GetDirectories(path);
				DirectoryInfo dirInfo = new DirectoryInfo(path);
				//files
				FileInfo[] files = dirInfo.GetFiles();
				if (files.Length > 0 || dir.Length > 0) {
					files.ToList().ForEach(file => {
						if ((!string.IsNullOrEmpty(extName)) && extName.ToLower().IndexOf(file.Extension.ToLower()) >= 0) {
							retVal.Add(file);
						} else {
							retVal.Add(file);
						}
					});
				}
				//sub directory
				dir.ToList().ForEach(d => {
					retVal.AddRange(WalkDirecotry(d, extName));
				});
			} catch { 
			
			}
			return retVal;
		}
		#endregion
	}
}
